/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pig.goods.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.goods.entity.TbGoods;
import com.pig4cloud.pig.goods.entity.TbItem;
import com.pig4cloud.pig.goods.service.TbGoodsService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;


/**
 * 
 *
 * @author pig code generator
 * @date 2021-07-15 19:29:58
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tbgoods" )
@Api(value = "tbgoods", tags = "管理")
public class TbGoodsController {

	@Autowired
    private final TbGoodsService tbGoodsService;

	@Autowired
	RestHighLevelClient esRestClient;

    /**
     * 分页查询
     * @param page 分页对象
     * @param tbGoods 
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('goods_tbgoods_get')")
    public R getTbGoodsPage(Page page, TbGoods tbGoods) {
        return R.ok(tbGoodsService.page(page, Wrappers.query(tbGoods)));
    }


    /**
     * 通过id查询
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('goods_tbgoods_get')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(tbGoodsService.getById(id));
    }

    /**
     * 新增
     * @param tbGoods 
     * @return R
     */
    @ApiOperation(value = "新增", notes = "新增")
    @SysLog("新增" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('goods_tbgoods_add')" )
    public R save(@RequestBody TbGoods tbGoods) {
        return R.ok(tbGoodsService.save(tbGoods));
    }

    /**
     * 修改
     * @param tbGoods 
     * @return R
     */
    @ApiOperation(value = "修改", notes = "修改")
    @SysLog("修改" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('goods_tbgoods_edit')" )
    public R updateById(@RequestBody TbGoods tbGoods) {
        return R.ok(tbGoodsService.updateById(tbGoods));
    }

    /**
     * 通过id删除
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @SysLog("通过id删除" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('goods_tbgoods_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(tbGoodsService.removeById(id));
    }

	/**
	 * 上架
	 * @return R
	 */
	@ApiOperation(value = "上架", notes = "上架")
	@SysLog("上架" )
	@PostMapping("putaway")
	@PreAuthorize("@pms.hasPermission('goods_tbgoods_putaway')" )
	public Object putaway(@RequestBody TbItem TbItem) throws IOException, TemplateException {
		TbItem.setStatus("1");
		/*处理图片格式*/
		TbItem.setImage("http://"+TbItem.getImage());
		/*生成静态页面*/
		makefreemarker(TbItem);
		int putaway = tbGoodsService.putaway(TbItem);

		if(putaway>0){
			/*将上架的商品添加到索引库*/
			IndexRequest pinyougoudb = new IndexRequest("pinyougoudb");
			pinyougoudb.source(JSON.toJSONString(TbItem), XContentType.JSON);
			esRestClient.index(pinyougoudb, RequestOptions.DEFAULT);
			return true;
		}
		return false;
	}

	/*生成静态页面*/
	public void makefreemarker(TbItem tbItem) throws IOException, TemplateException {
		//创建配置对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		//设置默认生成文件编码
		configuration.setDefaultEncoding("utf-8");
		//设置模板路径
		configuration.setClassForTemplateLoading(this.getClass(), "/templates");
		//获取模板
		Template template = configuration.getTemplate("index.ftl");
		//加载数据
		Map<String, Object> dataModel  =new HashMap<String, Object>();
		dataModel.put("name", "商品详情");
		dataModel.put("message", tbItem.getTitle());

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("name", tbItem.getTitle());
		map1.put("price", tbItem.getPrice());
		map1.put("spec", tbItem.getSpec());
		map1.put("image", tbItem.getImage());
		list.add(map1);

		dataModel.put("goodsList", list);
		dataModel.put("today", new Date());
		dataModel.put("number", 123456789L);
		//创建输出对象,将文件输出到D盘根目录下
		FileWriter fileWriter = new FileWriter("D:/freemarker/"+tbItem.getTitle()+".html");
		//渲染模板和数据
		template.process(dataModel, fileWriter);
		//关闭输出
		fileWriter.close();
	}

}
